import { ref } from 'vue'
import { showToast } from 'vant'

export const useList = (fetchApi, id) => {
  // 刷新状态
  const refreshing = ref(false)
  // 加载状态
  const loading = ref(false)
  // 是否加载完成
  const finished = ref(false)
  // 列表数据
  const list = ref([])
  // 当前页码
  const pageNum = ref(1)
  // 每页大小
  const pageSize = 20
  // 总数
  const total = ref(0)
  // 搜索值
  const searchValue = ref('')

  // 获取列表数据
  const getList = async (isRefresh = false) => {
    if (loading.value && !isRefresh) return
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize,
        keyword: searchValue.value,
      }

      const res = await fetchApi(id, params)
      const listData = res.follows || res.fans || []
      total.value = res.total

      if (isRefresh) {
        list.value = listData
        refreshing.value = false
        pageNum.value = 1
        finished.value = listData.length >= total.value
      } else {
        list.value = [...list.value, ...listData]
        if (listData.length < pageSize) {
          finished.value = true
        } else {
          pageNum.value++
        }
      }
    } catch (error) {
      console.error(error)
      showToast('加载失败')
    } finally {
      loading.value = false
      if (isRefresh) {
        refreshing.value = false
      }
    }
  }

  // 搜索处理
  const handleSearch = () => {
    pageNum.value = 1
    list.value = []
    finished.value = false
    getList()
  }

  // 下拉刷新
  const onRefresh = () => {
    getList(true)
  }

  // 上拉加载
  const onLoad = () => {
    if (!finished.value) {
      getList()
    }
  }

  return {
    refreshing,
    loading,
    finished,
    list,
    searchValue,
    getList,
    handleSearch,
    onRefresh,
    onLoad,
  }
}
